package com.example.thegreatwall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.thegreatwall.common.R;
import com.example.thegreatwall.common.api.CommonResult;
import com.example.thegreatwall.entity.Comment;
import com.example.thegreatwall.entity.Product;
import com.example.thegreatwall.entity.TProduct;
import com.example.thegreatwall.service.CommentService;
import com.example.thegreatwall.service.ProductService;
import com.example.thegreatwall.service.TProductService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品管理控制器
 * 处理商品的基本信息，包括列表查询、详情查看、分类查询和搜索功能
 */
@RestController
@RequestMapping("/product")
@CrossOrigin(origins = "*")
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private TProductService tProductService;


    /**
     * 获取商品列表
     * 支持分页查询、按商品类型筛选和关键词搜索
     *
     * @param pageNum 当前页码，默认1
     * @param pageSize 每页数量，默认20
     * @param productTypeId 商品类型ID，可选参数
     * @param keyword 搜索关键词，可选参数
     * @return 返回分页的商品列表数据
     */
    @GetMapping("/list")
    public CommonResult<Page<Product>> listProducts(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
            @RequestParam(value = "productTypeId", required = false) Integer productTypeId,
            @RequestParam(value = "keyword", required = false) String keyword) {
        
        Page<Product> productList;
        if (keyword != null && !keyword.trim().isEmpty()) {
            // 如果有关键词，执行搜索
            productList = productService.searchProducts(keyword, pageNum, pageSize);
        } else {
            // 否则按类型查询
            productList = productService.listProducts(pageNum, pageSize, productTypeId);
        }
        return CommonResult.success(productList);
    }

    /**
     * 获取商品详情
     * 根据商品ID获取单个商品的详细信息
     *
     * @param productId 商品ID
     * @return 返回商品详细信息
     */
    @GetMapping("/detail/{productId}")
    public CommonResult<Product> getProductDetail(@PathVariable Integer productId) {
        Product product = productService.getProductDetail(productId);
        return CommonResult.success(product);
    }

    /**
     * 按类型获取商品列表
     * 根据商品类型ID获取对应的商品列表
     *
     * @param productTypeId 商品类型ID
     * @param pageNum 当前页码，默认1
     * @param pageSize 每页数量，默认20
     * @return 返回分页的商品列表数据
     */
    @GetMapping("/type/{productTypeId}")
    public CommonResult<Page<Product>> getProductsByType(
            @PathVariable Integer productTypeId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        Page<Product> productList = productService.getProductsByType(productTypeId, pageNum, pageSize);
        return CommonResult.success(productList);
    }

    /**
     * 搜索商品
     * 根据关键词搜索商品名称和描述
     *
     * @param keyword 搜索关键词
     * @param pageNum 当前页码，默认1
     * @param pageSize 每页数量，默认20
     * @return 返回分页的搜索结果
     */
    @GetMapping("/search")
    public CommonResult<Page<Product>> searchProducts(
            @RequestParam String keyword,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        Page<Product> searchResult = productService.searchProducts(keyword, pageNum, pageSize);
        return CommonResult.success(searchResult);
    }

    /**
     * 根据id查询产品
     * @param id 产品id
     * @return
     */
    @GetMapping("/getProductById")
    public R getProductById(@Param("id") Integer id){
        Product product = productService.getById(id);
        //计算这个商品评分
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id",id);
        queryWrapper.eq("product_type",1);
        List<Comment> comments = commentService.list(queryWrapper);
        BigDecimal num=new BigDecimal(0);
        for (Comment comment : comments) {
//            System.out.println(comment.getScore());
            num=num.add(comment.getScore());
        }
        // 1 表示保留 1 位小数，ROUND_HALF_UP 是四舍五入模式
        BigDecimal num2=new BigDecimal(comments.size());
        if (comments.size()>0){
            product.setScore(num.divide(num2,2,BigDecimal.ROUND_HALF_UP));
        }

        System.out.println("这是我算出的分数："+product.getScore());
        QueryWrapper<Product> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("product_id",id);
        boolean update = productService.update(product,queryWrapper1);
        return new R().addDate("product", product);
    }

    /**
//     * 根据类型id查询产品
//     * @param typeid 类型id
     * @return
     */
    @GetMapping("/getProductByType")
    public R getProductByType(){
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);//商品未下架
        queryWrapper.orderByAsc("rand()");
        queryWrapper.last("limit 6");

        List<Product> list = productService.list(queryWrapper);
        return new R().addDate("productList", list);
    }

    @GetMapping(value = "updcountnum")
    public void updcountnum(@RequestParam Integer id, @RequestParam Integer type){

        if(type==0){
            UpdateWrapper<Product> productUpdateWrapper = new UpdateWrapper<>();
            productUpdateWrapper.eq("product_id",id).setSql("countnum = countnum + 1");
            productService.update(null, productUpdateWrapper);
        }else {
            UpdateWrapper<TProduct> productUpdateWrapper = new UpdateWrapper<>();
            productUpdateWrapper.eq("t_product_id",id).setSql("countnum = countnum + 1");
            tProductService.update(null, productUpdateWrapper);
        }

    }
    @GetMapping(value = "proname")
    public List<Product> proname(@RequestParam String pid) {
        System.out.println("pppppppppppppppppppppppp:"+pid);
        List<Integer> ids = Arrays.stream(pid.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        System.out.print(ids);
        return productService.proname(ids);
    }

}